package com.tanhua.admin.service;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.commons.utils.ConstantUtil;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.dubbo.api.*;
import com.tanhua.model.mongo.LockMassage;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.MovementsVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VideoVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ManageService {

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private VideoApi videoApi;

    @DubboReference
    private MovementApi movementApi;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @DubboReference
    private UserFreezeApi userFreezeApi;

    @DubboReference
    private  UserApi userApi;

    public  Map<String, String> lockUser(LockMassage lockMassage) {
        //根据UserId查询用户
        UserInfo userInfo = userInfoApi.findById(Long.valueOf(lockMassage.getUserId()));
        //把用户冻结状态改为2
        userInfo.setUserStatus("2");
        //修改用户状态
        userInfoApi.update(userInfo);
        //冻结用户
        Long userId = userInfo.getId();
        userFreezeApi.save(lockMassage);
        Integer freezingRange = lockMassage.getFreezingRange();//冻结范围
        //冻结信息根据传入参数设置生命周期
        if (lockMassage.getFreezingTime() == 1) {
            //往rides中存入冻结信息，用户登录时查询rides如果有该用户的冻结信息，则不会登录
            stringRedisTemplate.opsForValue().set(ConstantUtil.LOCK_USER + userId, freezingRange + "", Duration.ofDays(3));
        } else if (lockMassage.getFreezingTime() == 2) {
            //往rides中存入冻结信息，用户登录时查询rides如果有该用户的冻结信息，则不会登录
            stringRedisTemplate.opsForValue().set(ConstantUtil.LOCK_USER + userId, freezingRange + "", Duration.ofDays(7));
        } else if (lockMassage.getFreezingTime() == 3) {
            //往rides中存入冻结信息，用户登录时查询rides如果有该用户的冻结信息，则不会登录
            stringRedisTemplate.opsForValue().set(ConstantUtil.LOCK_USER + userId, freezingRange + "");
        }
        Map<String, String> map = new HashMap<>();
        map.put("message", "操作成功，冻结原因" + lockMassage.getReasonsForFreezing());
        //删除用户token
        Map<String, Object> tokenMap = new HashMap<>();
        tokenMap.put("id", userId);
        String phone = userApi.findPhoneById(userId);
        tokenMap.put("phone", phone);
        String token = JwtUtils.getToken(tokenMap);//用户token
        stringRedisTemplate.delete(ConstantUtil.USER_TOKEN + token);
        return map;
    }

    public  Map unfreeze(Long userId, String reasonsForThawing) {
        //删除mongo的user_freeze表中的冻结数据并删除redis中的冻结终止时间的缓存数据
        userFreezeApi.delete(userId);
        //删除redis缓存中的冻结用户标识符
        String key = ConstantUtil.LOCK_USER + userId;
        stringRedisTemplate.delete(key);
        //将该用户的冻结字段改为1
        UserInfo userInfo = userInfoApi.findById(userId);
        userInfo.setUserStatus("1");
        userInfoApi.update(userInfo);
        HashMap map = new HashMap<>();
        map.put("message", "解冻原因：" + reasonsForThawing);
        return map;
    }

    /**
     * 分页查询所有的探花用户信息
     *   userInfo
     */
    public PageResult users(Integer page, Integer pagesize) {
        //1、调用API分页查询UserInfo  IPage
        IPage iPage = userInfoApi.findAll(page,pagesize); //分页pagebean
        //2、构造PageResult
        return new PageResult(page,pagesize,iPage.getTotal(),iPage.getRecords());
    }

    //根据id查询用户详情
    public UserInfo findUserById(Long userId) {
        return userInfoApi.findById(userId);
    }

    //根据用户id，分页查询视频列表
    public PageResult findVideos(Long userId, Integer page, Integer pagesize) {
        //1、调用API查询，返回分页数据  PageResult （分页列表，总数）  --- List<Video>
        PageResult result = videoApi.findByUserId(userId,page,pagesize);
        //2、从PageResult获取list    -- List<Video>
        List<Video> items = (List<Video>) result.getItems();
        if(CollUtil.isEmpty(items)) {
            return result;
        }
        List<Long> userIds = CollUtil.getFieldValues(items, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds);
        //3、将List<Video>  转化成   List<VideoVo>
        List<VideoVo> vos = new ArrayList<>();
        for (Video item : items) {
            UserInfo info = map.get(item.getUserId());//视频作者的信息
            VideoVo vo = VideoVo.init(info, item);
            vos.add(vo);
        }
        //4、将List<VideoVo>替换到PageResult的list集合
        result.setItems(vos);
        return result;
    }

    //分页查询动态列表
    public PageResult findMovements(Integer state, Long userId, Integer page, Integer pagesize) {
        //1、调用API分页查询动态    PageResult  --List<Movement>
        PageResult result =  movementApi.findAll(state,userId,page,pagesize);
        //2、从PageResult获取list    -- List<Movement>
        List<Movement> items = (List<Movement>) result.getItems();
        if(CollUtil.isEmpty(items)) {
            return result;
        }
        List<Long> userIds = CollUtil.getFieldValues(items, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds);
        //3、将List<Movement>  转化成   List<MovementVo>
        List<MovementsVo> vos = new ArrayList<>();
        for (Movement item : items) {
            UserInfo info = map.get(item.getUserId());
            MovementsVo vo = MovementsVo.init(info, item);
            vos.add(vo);
        }
        //4、将List<MovementVo>替换到PageResult的list集合
        result.setItems(vos);
        return result;
    }
}
